﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Xwy.Practical.Models;
using Xwy.Practical.Options;
using Xwy.Practical.Utils;
using Xwy.Practical.ViewModels;

namespace Xwy.Practical.Controllers
{
    public class TestController : Controller
    {
        IUserinfoRepository _iUserinfoRepository;
        MockUserinfoRepository _mockUserinfoRepository;
        MockUserinfoService _mockUserinfoService;

        G<Userinfo> _user;
        G<Role> _role;

        IG<Userinfo> _iguser;
        IG<Role> _igrole;

        IConfiguration _iConfiguration;

        IOptions<PositionOptions> _posOpt;
        IHostEnvironment _hostEnvironment;
        IMemoryCache _memoryCache;
        IDistributedCache _distributedCache;
        ILogger<TestController> _logger;

        public TestController(ILogger<TestController> logger,IDistributedCache distributedCache,IMemoryCache memoryCache ,IHostEnvironment hostEnvironment ,IOptions<PositionOptions> posOpt,IConfiguration configuration, IG<Userinfo> iguser, IG<Role> igrole, G<Userinfo> user,G<Role> role,IUserinfoRepository userinfoRepository, MockUserinfoRepository mockUserinfoRepository,MockUserinfoService mockUserinfoService)
        {
            _logger = logger;
            _distributedCache = distributedCache;
            _memoryCache = memoryCache;
            _hostEnvironment = hostEnvironment;
             _posOpt = posOpt;
            _iUserinfoRepository = userinfoRepository;
            _mockUserinfoRepository = mockUserinfoRepository;
            _mockUserinfoService = mockUserinfoService;
            _user = user;
            _role = role;

            _igrole = igrole;
            _iguser = iguser;

            _iConfiguration = configuration;
        }
        public IActionResult Index()
        {
            ViewBag.Nowtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:SS");
            return View();
        }

        public string Index2()
        {
            _logger.LogDebug("我是debug");
            _logger.LogInformation("我是info");
            _logger.LogWarning("我是warm");
            //_logger.LogError("我是err");
            var str = DateTime.Now.ToString("yyyy-MM-dd HH:mm:SS");

            var myKeyValue = _iConfiguration["MyKey"];
            var title = _iConfiguration["Position:Title"];
            var name = _iConfiguration["Position:Name"];
            var defaultLogLevel = _iConfiguration["Logging:LogLevel:Default"];
            str = $"MyKey value: {myKeyValue} \n" +
                       $"Title: {title} \n" +
                       $"Name: {name} \n" +
                       $"Default Log Level: {defaultLogLevel}";

            var posOpt = _iConfiguration.GetSection("Position").Get<PositionOptions>();
            bool dfg = posOpt.Equals(_posOpt.Value);

            return str;
        }

        public IActionResult SendEmail() 
        {
            return View();
        }

        [HttpPost]
        public IActionResult SendEmail(SendEmailVM sendEmailVM)
        {
            if (ModelState.IsValid) 
            {
                MailMessage mailMessage = new MailMessage();
                mailMessage.From = new MailAddress("1298630969@qq.com","xwy");
                mailMessage.To.Add(new MailAddress(sendEmailVM.ReceiveEmail));
                mailMessage.Subject = sendEmailVM.Suject;
                mailMessage.Body = sendEmailVM.Content;

                SmtpClient client = new SmtpClient();
                client.Host = "smtp.qq.com";

                client.Port = 587;
                client.EnableSsl = true;
                client.Credentials = new NetworkCredential("1298630969@qq.com", "askjcrgsjtvdiahc");
                try
                {
                    client.Send(mailMessage);
                }
                catch (SmtpException ex) {
                    return Ok("发送失败"+ex.Message);
                }

                return Ok("发送成功");
            }
            return View();
        }

        public IActionResult Verifycode() 
        {
            return File(new VerifycodeService().GetVerifyCode(),"image/gif") ;
        }

        public IActionResult GetQRCode(string plain="你好" ,int pixel=2) 
        {
            if (pixel <= 0)
            {
                return BadRequest("pixel <= 0");
            }
            return File(new QRCodeService().GetQRCode(plain,pixel), "image/jpeg");
        }

        public IActionResult GetWifyQRCode(int pixel = 16)
        {
            if (pixel <= 0)
            {
                return BadRequest("pixel <= 0");
            }
            string plain = "123456";
            return File(new QRCodeService().GetQRCode(plain, pixel), "image/jpeg");
        }

        public IActionResult GetWifyQRCodeLogo(int pixel = 16)
        {
            if (pixel <= 0)
            {
                return BadRequest("pixel <= 0");
            }
            string plain = "123456";
            string logoPath = @"Files/my.jpg";
            return File(new QRCodeService().GetQRCodeWithLogo(plain, pixel, logoPath), "image/jpeg");
        }


        public IActionResult Upload() 
        {
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Upload(List<IFormFile> files2)
        {
            var files = Request.Form.Files;
            long size = files.Sum(f => f.Length);
            string contentRootPath = _hostEnvironment.ContentRootPath;

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {

                    string fileExt = GetFileExt(formFile.FileName); //文件扩展名，不含“.”
                    long fileSize = formFile.Length; //获得文件大小，以字节为单位
                    string newFileName = System.Guid.NewGuid().ToString()  + fileExt; //随机生成新的文件名
                    var uploadPath = contentRootPath + "/Upload/";
                    if (!Directory.Exists(uploadPath)) 
                    {
                        Directory.CreateDirectory(uploadPath);
                    }
                    var filePath = uploadPath+newFileName;
                    using (var stream = new FileStream(filePath,FileMode.Create))
                    {

                        await formFile.CopyToAsync(stream);
                    }
                }
            }

            return Ok(new { count = files.Count, size });
        }

        private string GetFileExt(string fileName)
        {
            return fileName.Substring(fileName.LastIndexOf('.'));
        }

        /// <summary>
        /// 文件流的方式输出        /// </summary>
        /// <returns></returns>
        public IActionResult DownLoad(string file)
        {
            string contentRootPath = _hostEnvironment.ContentRootPath;
            var uploadPath = contentRootPath + "/Upload/";

            var addrUrl = uploadPath+file;
            var stream = System.IO.File.OpenRead(addrUrl);
            //获取文件的ContentType
            //string fileExt = GetFileExt(file).Substring(1);
            //var provider = new FileExtensionContentTypeProvider();
            //var memi = provider.Mappings[fileExt];
            var memi = "text/plain";
            return File(stream, memi, Path.GetFileName(addrUrl));
        }



        public IActionResult Cache() 
        {
            string key = "NowTime";
            string value = _memoryCache.Get<string>(key);
            if (value==null)
            {
                value= DateTime.Now.ToString();
                _memoryCache.Set(key, value,TimeSpan.FromSeconds(10));//10秒后过期             
            }
            ViewBag.NowTime = value;

            return View();
        }
        public async Task<IActionResult> RedisCache()
        {
            string key = "NowTime";
            string value = await _distributedCache.GetStringAsync(key);
            if (value == null)
            {
                value ="redis time:"+DateTime.Now.ToString();
                DistributedCacheEntryOptions cacheEntryOptions = new DistributedCacheEntryOptions
                {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(15)
                };
                await _distributedCache.SetStringAsync(key, value,cacheEntryOptions);//15秒后过期             
            }
            ViewBag.NowTime = value;

            return View();
        }
    }
}